using BasicData.API.Application.Command;
using BasicData.API.Application.Mediator;
using BasicData.API.Dtos;
using BasicData.ErrorCode;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace BasicData.API.Controllers
{
    /// <summary>
    /// 生产信息修改控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ProductionUpdateController : ControllerBase
    {
        private readonly IProductionInfoMediator _productionInfoMediator;
        private readonly ILogger<ProductionUpdateController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoMediator">生产信息中介者</param>
        /// <param name="logger">日志</param>
        public ProductionUpdateController(
            IProductionInfoMediator productionInfoMediator,
            ILogger<ProductionUpdateController> logger)
        {
            _productionInfoMediator = productionInfoMediator;
            _logger = logger;
        }

        /// <summary>
        /// 修改生产信息
        /// </summary>
        /// <param name="command">修改命令</param>
        /// <returns>修改结果</returns>
        [AllowAnonymous]
        [HttpPut]
        public async Task<APIResult<ProductionInfoDTO>> UpdateProductionInfo(UpdateProductionInfoCommand command)
        {
            try
            {
                _logger.LogInformation("开始修改生产信息，ID：{Id}，批次：{BatchNumber}，图片URL：{CoverImageUrl}", 
                    command.Id, command.BatchNumber, command.CoverImageUrl);

                if (command.Id == Guid.Empty)
                {
                    _logger.LogWarning("生产信息ID为空");
                    return new APIResult<ProductionInfoDTO>
                    {
                        Code = ResultCode.更新失败,
                        Message = "生产信息ID不能为空"
                    };
                }

                if (string.IsNullOrWhiteSpace(command.ModifiedBy))
                {
                    _logger.LogWarning("操作人为空");
                    return new APIResult<ProductionInfoDTO>
                    {
                        Code = ResultCode.更新失败,
                        Message = "操作人不能为空"
                    };
                }

                // 调用中介者执行修改
                var result = await _productionInfoMediator.UpdateProductionInfoAsync(command);

                _logger.LogInformation("修改生产信息完成，ID：{Id}，结果：{Result}，数据：{Data}", 
                    command.Id, result.Code, result.Data != null ? "有数据" : "无数据");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改生产信息时发生错误，ID：{Id}，错误：{Error}", command.Id, ex.Message);
                return new APIResult<ProductionInfoDTO>
                {
                    Code = ResultCode.更新失败,
                    Message = $"修改生产信息失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据ID获取生产信息（包含商品信息）
        /// </summary>
        /// <param name="id">生产信息ID</param>
        /// <returns>生产信息</returns>
        [AllowAnonymous]
        [HttpGet("{id}")]
        public async Task<APIResult<ProductionInfoWithGoodsDTO>> GetProductionInfoById(Guid id)
        {
            try
            {
                _logger.LogInformation("开始获取生产信息，ID：{Id}", id);

                if (id == Guid.Empty)
                {
                    return new APIResult<ProductionInfoWithGoodsDTO>
                    {
                        Code = ResultCode.查询失败,
                        Message = "生产信息ID不能为空"
                    };
                }

                // 创建查询命令
                var command = new GetProductionInfoByIdCommand { Id = id };

                // 调用中介者执行查询
                var result = await _productionInfoMediator.GetProductionInfoByIdAsync(command);

                _logger.LogInformation("获取生产信息完成，ID：{Id}，结果：{Result}", id, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产信息时发生错误，ID：{Id}", id);
                return new APIResult<ProductionInfoWithGoodsDTO>
                {
                    Code = ResultCode.查询失败,
                    Message = $"获取生产信息失败: {ex.Message}"
                };
            }
        }
    }
} 
